package top.fyxxxx.downloader.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.os.Message;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadManager {
    private static DownloadManager instance;
    private ThreadPoolExecutor executor;
    private MyHandler handler;
    private DownloadManager(Context context){
        executor=(ThreadPoolExecutor) Executors.newFixedThreadPool(SqlUtil.getInstance(context).getThreadNum());
        handler=new MyHandler();
    }
    public static DownloadManager getInstance(Context context){
        if(instance==null) {
            synchronized (DownloadManager.class) {
                if (instance == null) {
                    instance=new DownloadManager(context);
                }
            }
        }
        return instance;
    }
    public DownloadTask getTask(String url,String savepath){
        DownloadTask task=new DownloadTask(url, savepath,executor,handler);
        return task;
    }
    public static Response download(String url, final long start) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .header("RANGE", "bytes=" + start + "-")//断点续传
                .build();

        // 重写ResponseBody监听请求
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new DownloadResponseBody(originalResponse))
                        .build();
            }
        };

        OkHttpClient.Builder dlOkhttp = new OkHttpClient.Builder()
                .addNetworkInterceptor(interceptor);
        // 绕开证书
        try {
            //setSSL(dlOkhttp);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 发起请求
        Call call = dlOkhttp.build().newCall(request);
        return call.execute();
    }

    public void setThreadNum(int n){
        executor.setCorePoolSize(n);
    }


    public static class MyHandler extends android.os.Handler {
        MyHandler() {
            super(Looper.getMainLooper());
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DownloadCallback result=(DownloadCallback) msg.obj;
            result.execute();
        }
    }
    interface DownloadCallback{
        void execute();
    }
}
